import axios from 'axios'
import { Message } from '@arco-design/web-vue';
import router from '@/router/index.js'
import Cookies from 'js-cookie'

const TOKEN_INVALID = 'token过期, 请重新登录!'
const NETWORK_ERROR = '网络请求错误，请稍后重试!'
const USER_ACCOUNT_ERROR = '账号或密码错误'

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 8000
})

service.interceptors.request.use(
    config => {
        const headers = config.headers
        const token = Cookies.get('gn-token') ? Cookies.get('gn-token') : ''
        if (!headers.Authorization) headers.Authorization = token
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    response => {
        const { code, msg } = response.data
        if (code === 200) {
            if (msg) Message.success(msg)
            return response
        } else if (code === 20001) { // 账号或密码错误
            Message.error(msg || USER_ACCOUNT_ERROR)
            return Promise.reject(msg || USER_ACCOUNT_ERROR)
        } else if (code === 50001) { //token过期
            Message.error(TOKEN_INVALID)
            setTimeout(() => {
                router.push('/login')
            }, 1500);
            return Promise.reject(TOKEN_INVALID) // 控制台可以看到
        } else {
            Message.error(msg || NETWORK_ERROR)
            return Promise.reject(msg || NETWORK_ERROR)
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
